package com.specter.mvc.model;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.ibatis.type.Alias;

@Alias("jmap")
public class ResultMap extends HashMap<String, Object> {
    // 正则匹配下划线和紧随的字母（不区分大小写）
    private static final Pattern UNDERLINE_PATTERN = Pattern.compile("_([A-Za-z])");

    @Override
    public Object put(String key, Object value) {
        String camelKey = toCamelCase(key);
        return super.put(camelKey, value);
    }

    /**
     * 下划线转驼峰（兼容全大写字段名）
     * - USER_NAME → userName
     * - user_name → userName
     */
    private String toCamelCase(String key) {
        // 先将整个 key 转为小写，确保统一处理
        String lowerKey = key.toLowerCase();
        Matcher matcher = UNDERLINE_PATTERN.matcher(lowerKey);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            // 将匹配到的字母转为大写
            String replacement = matcher.group(1).toUpperCase();
            matcher.appendReplacement(sb, replacement);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}